<template>
  <div v-if="open" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
    <div class="card w-full max-w-lg">
      <div class="text-lg font-semibold mb-2">{{ isEditMode ? '编辑喂奶记录' : '记录喂奶' }}</div>
      <form class="space-y-3" @submit.prevent="save">
        <label class="block">
          <span class="text-sm">时间</span>
          <input class="input mt-1" type="datetime-local" v-model="formTimeLocal" />
        </label>
        <div>
          <div class="text-sm mb-2">类型</div>
          <div class="flex gap-2">
            <button type="button" class="px-3 py-1 rounded"
              :class="feedingType==='BREAST_MILK' ? 'bg-primary text-white' : 'bg-bg'"
              @click="feedingType='BREAST_MILK'">母乳</button>
            <button type="button" class="px-3 py-1 rounded"
              :class="feedingType==='FORMULA' ? 'bg-primary text-white' : 'bg-bg'"
              @click="feedingType='FORMULA'">配方奶</button>
          </div>
        </div>

        <div v-if="feedingType==='BREAST_MILK'" class="grid grid-cols-2 gap-3">
          <label class="block">
            <span class="text-sm">左侧（分钟）</span>
            <input class="input mt-1" type="number" min="0" v-model.number="leftMinutes" />
          </label>
          <label class="block">
            <span class="text-sm">右侧（分钟）</span>
            <input class="input mt-1" type="number" min="0" v-model.number="rightMinutes" />
          </label>
        </div>
        <div v-else>
          <label class="block">
            <span class="text-sm">奶量（ml）</span>
            <input class="input mt-1" type="number" min="0" v-model.number="formulaMl" />
          </label>
        </div>

        <label class="block">
          <span class="text-sm">备注</span>
          <textarea class="input mt-1" rows="3" placeholder="可输入备注...（可选）" v-model="note" />
        </label>

        <div class="flex gap-2">
          <button type="submit" class="btn-primary flex-1" :disabled="loading">
            {{ loading ? '保存中...' : '保存' }}
          </button>
          <button type="button" class="btn-accent flex-1" @click="$emit('update:open', false)">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useUserStore } from '../stores/user';
import { API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function createFeeding(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('FeedingModal createFeeding - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/feeding`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function updateFeeding(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('FeedingModal updateFeeding - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/feeding/${payload.id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

const props = defineProps<{ 
  open: boolean;
  editData?: any; // 编辑时的数据
}>();
const emit = defineEmits<{ 
  (e: 'update:open', v: boolean): void;
  (e: 'saved'): void;
}>();
const userStore = useUserStore();

const feedingType = ref<'BREAST_MILK' | 'FORMULA'>('FORMULA');
const leftMinutes = ref<number | undefined>();
const rightMinutes = ref<number | undefined>();
const formulaMl = ref<number | undefined>();
const note = ref('');
const loading = ref(false);

const formTimeLocal = ref<string>('');
const isEditMode = computed(() => !!props.editData);

watch(
  () => props.open,
  (v) => {
    if (v) {
      if (props.editData) {
        // 编辑模式：填充现有数据
        const editTime = new Date(props.editData.eventTime);
        formTimeLocal.value = new Date(editTime.getTime() - editTime.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        feedingType.value = props.editData.feedingType;
        leftMinutes.value = props.editData.leftMinutes;
        rightMinutes.value = props.editData.rightMinutes;
        formulaMl.value = props.editData.formulaMl;
        note.value = props.editData.note || '';
      } else {
        // 新建模式：使用当前时间
        const now = new Date();
        formTimeLocal.value = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        // 重置表单
        feedingType.value = 'FORMULA';
        leftMinutes.value = undefined;
        rightMinutes.value = undefined;
        formulaMl.value = undefined;
        note.value = '';
      }
    }
  }
);

const eventTime = computed(() => new Date(formTimeLocal.value).toISOString());

async function save() {
  if (!userStore.currentBabyId) {
    alert('请先选择宝宝');
    return;
  }

  try {
    loading.value = true;
    
    if (isEditMode.value) {
      // 编辑模式：调用更新API
      await updateFeeding({
        id: props.editData.id,
        babyId: userStore.currentBabyId,
        eventTime: eventTime.value,
        feedingType: feedingType.value,
        leftMinutes: feedingType.value === 'BREAST_MILK' ? leftMinutes.value : undefined,
        rightMinutes: feedingType.value === 'BREAST_MILK' ? rightMinutes.value : undefined,
        formulaMl: feedingType.value === 'FORMULA' ? formulaMl.value : undefined,
        note: note.value || undefined
      });
    } else {
      // 新建模式：调用创建API
      await createFeeding({
        babyId: userStore.currentBabyId,
        eventTime: eventTime.value,
        feedingType: feedingType.value,
        leftMinutes: feedingType.value === 'BREAST_MILK' ? leftMinutes.value : undefined,
        rightMinutes: feedingType.value === 'BREAST_MILK' ? rightMinutes.value : undefined,
        formulaMl: feedingType.value === 'FORMULA' ? formulaMl.value : undefined,
        note: note.value || undefined
      });
    }
    
    emit('saved');
    emit('update:open', false);
  } catch (error) {
    console.error('保存喂奶记录失败:', error);
    alert('保存失败，请重试');
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped></style>